package comlib.bundle 

import chisel3._ 
import chisel3.util._

/** TDM状态传递接口
 * @group Interface
 */
class Tdm(dataWid:Int, segNum:Int=1) extends Bundle {
  /** 传输周期开始标识
   * @group IO
   */
  val start = Output(Bool())
  /** 传输内容
   * @group IO
   */
  val status = Output(UInt((dataWid*segNum).W))

  override def cloneType = new Tdm(dataWid, segNum).asInstanceOf[this.type]
}

object Tdm{
  /** 构造函数
   */
  def apply( dataWid:Int, segNum:Int=1 ) = new Tdm(dataWid, segNum)

  /** 接口加载电路
   * @param status 需要加载的状态信号
   * @param dataWid 每个域段的宽度
   * @param segNum 每次传递的域段个数
   * @return T接口Bundle变量
   */
  def encapsulate( status:UInt, dataWid:Int, segNum:Int ) : Tdm = {
    val period = status.getWidth / dataWid / segNum
    val tdm_cnt = RegInit( 0.U(log2Ceil(period).W) )
    val inner_status = VecInit(status.asBools().grouped( dataWid * segNum ).map(VecInit(_).asUInt()).toSeq)

    tdm_cnt := Mux( tdm_cnt===(period-1).U, 0.U, tdm_cnt+1.U )

    val ret = new Tdm( dataWid, segNum )
    ret.start := tdm_cnt===0.U 
    ret.status := inner_status( tdm_cnt )

    ret
  }
}